package com.iuie.ns.frame.utils.httpclients;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;

/**
 * http请求响应的结果封装
 * @author liujie
 * @date 2018年6月2日下午2:39:54
 */
public class HttpResult {

	private HttpEntity httpEntity;
	
	private CloseableHttpClient client;
	
	private CloseableHttpResponse resp;
	
	public HttpResult(HttpEntity httpEntity, CloseableHttpClient client, CloseableHttpResponse resp) {
		this.httpEntity = httpEntity;
		this.client = client;
		this.resp = resp;
	}
	
	@SuppressWarnings("unchecked")
	public <T> T handleResult(HttpResultHandler<T> handler) {
		try {
			if (handler == null) {
				return (T) new DefaultHttpResultHandler().handle(this.httpEntity);
			}
			return handler.handle(this.httpEntity); 
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			HttpClientUtils.closeQuietly(this.client);
			HttpClientUtils.closeQuietly(this.resp);
		}
		return null;
	}
	
}
